<template>
    <div id="ws">

    </div>
</template>

<script>
    import { GetCookie } from '@/utils/jscookie'
    import { ws } from '@/utils/socket'
    import bus from '@/assets/evnetbus'
    var wk = ws

    wk.onmessage = function (event) {
        var dd = JSON.parse(event.data)
        switch (dd.cmd) {
            case 1:
                console.log("接收消息pingpong:", event.data)
                break
            case 2:
                console.log("接收消息heart:", event.data)
                break
            default:
                console.log("接收消息:", event.data)
                bus.$emit('receiveMsg', event.data)
        }
    };

    // 定时心跳检测
    setInterval(function () {
        console.log(wk)
        var userInfo = JSON.parse(GetCookie('_userinfo'));
        var msg = {
            user_id: userInfo.id,
            cmd: 2,
            content: "ping"
        }
        console.log("发送消息heart:",  msg)
        wk.send(JSON.stringify(msg))
    },1000 * 20)

    export default {
        name: "ws",
        data() {
            return {

            }
        },
        mounted(){
            bus.$on('sendMsg', function (data) {
                console.log("发送消息:", data)
                wk.send(data)
            })
        }
    }
</script>

<style scoped lang="css">

</style>